import Vue from 'vue'

const ua = navigator.userAgent
const isAndroid = /(Android);?[\s/]+([\d.]+)?/.test(ua)
const isIpad = /(iPad).*OS\s([\d_]+)/.test(ua)
const isIpod = /(iPod)(.*OS\s([\d_]+))?/.test(ua)
const isIphone = !isIpad && /(iPhone\sOS)\s([\d_]+)/.test(ua)
const isWechat = /micromessenger/i.test(ua)
const isAlipay = /alipayclient/i.test(ua)

// Applet:小程序 APP:APP应用应用程序 H5:Html网页 Wx:微信公众号
function getSourceID () {
  if (isWechat) {
    return (window.__wxjs_environment === 'miniprogram' || window.navigator.userAgent.toLowerCase().includes('miniprogram')) ? 'Applet' : 'Wx'
  } else if (Vue.$utils.UserAgent.getInfo()) {
    return 'APP'
  } else {
    return 'H5'
  }
}

const plugin = function (Vue) {
  // Vue.$device will be removed
  if (!Vue.$device || !Vue.device) {
    Vue.$device = Vue.device = {
      isAndroid,
      isIpad,
      isIpod,
      isIphone,
      isWechat,
      isAlipay,
      sourceID: getSourceID()
    }
  }
  Vue.mixin({
    created: function () {
      this.$device = {
        isAndroid,
        isIpad,
        isIpod,
        isIphone,
        isWechat,
        isAlipay,
        sourceID: getSourceID()
      }
    }
  })
}
export default plugin
